/**************************************************************************
 *
 * Copyright (C) 2007 University of California, Los Angeles.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 *************************************************************************/

package edu.ucla.cs.typecast.util;

import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;

/**
 * Utility class to retrieve type information. 
 * 
 * @date Jul 25, 2007
 */

public class TypeUtil {
	
	static public Class[] getInterfaces(Class curClass) { 
		HashSet<Class> interfaces = new HashSet<Class>(); 
		while(curClass != null) {
			Class[] directInterfaces = curClass.getInterfaces(); 
			if (directInterfaces != null) { 
				for(int i=0; i<directInterfaces.length; i++) { 
					if (isPublic(directInterfaces[i]) && !directInterfaces[i].getName().startsWith("java.")) { 
						interfaces.add(directInterfaces[i]); 
					}
				}
			}			
			curClass = curClass.getSuperclass(); 
		}
		return interfaces.toArray(new Class[interfaces.size()]) ; 		
	}
	
	/**
	 * Retrieve all the public interfaces
	 * @param types
	 * @return
	 */

	static public Collection<Class> getAllTypes(Class[] types) { 
		return getAllTypes(Arrays.asList(types)); 
	}

	static public Collection<Class> getAllTypes(Collection<Class> types) { 
		HashSet<Class> result = new HashSet<Class>(); 
		for(Class type: types) { 
			getAllTypes(result, type); 
		}
		return result; 
	}
	
	static private void getAllTypes(HashSet<Class> set, Class type) { 
		if (isPublic(type) && !type.getName().startsWith("java.")) { 
			set.add(type);
		}
		Class[] superTypes = type.getInterfaces(); 
		for(int i =0; i < superTypes.length; i++) { 
			getAllTypes(set, superTypes[i]); 
		}		
		//Also add super class if this is Class. This is designed to work for Event. 
		Class superClass = type.getSuperclass(); 
		if (superClass != null && superClass != Object.class) { 
			getAllTypes(set, superClass); 
		}
	}
		
	private static boolean isPublic(Class type) { 
		return (type.getModifiers() & Modifier.PUBLIC ) != 0; 
	}
	
}
